<?php

require_once(sfConfig::get('sf_plugins_dir').'/sfDoctrineGuardPlugin/modules/sfGuardRegister/lib/BasesfGuardRegisterActions.class.php');

/**
 * sfGuardRegister actions.
 *
 * @package    guard
 * @subpackage sfGuardRegister
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z jwage $
 */
class sfGuardRegisterActions extends BasesfGuardRegisterActions
{
  public function executeRegister(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated())
    {
      $this->getUser()->setFlash('notice', 'You are already registered and signed in!');
      $this->redirect('@homepage');
    } 

    $this->form = new sfGuardRegisterForm();

    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter($this->form->getName()));
      if ($this->form->isValid())
      {
        $user = $this->form->save();
        //$this->getUser()->signIn($user);
        $this->_enviaEmailActivacion($user);
        $this->setTemplate('comprobacion');
        //$this->redirect('@homepage');
      }
    }
  }

  protected function _enviaEmailActivacion($usuario)
  {
    $activ = new Activacion();
    $clave = (string) md5(rand() + time());
    $activ->setClave($clave);
    //$activ->setCreatedAt($fecha);
    $activ->setUsuarioNick($usuario->getUsername());
    $activ->setUsuarioId($usuario->getPrimaryKey());
    $usuario->setActivacion($activ);
    $activ->save();
    $usuario->save();
    
    $id = $usuario->getPrimaryKey();

    sfContext::getInstance()->getConfiguration()->loadHelpers('Url');
/*
    $link = link_to('activar cuenta','http://ecommerce.altarget.com:8383/ShoppingCartFront_dev.php/carrito/activar?confirm=' 
        . $activ->getClave() . '&' . 'id=' . $usuario->getPrimaryKey()) ;
*/
    $message = Swift_Message::newInstance()
      ->setFrom(sfConfig::get('app_sf_guard_plugin_default_from_email', 'clopez@altarget.net' ))
      ->setTo($usuario->getEmailAddress())
      ->setSubject('Confirmacion de registro de '. $usuario->getUsername())
      ->setBody($this->getPartial('email_activ', array('username' => $usuario->getUsername(), 'clave' => $clave, 'id' => $id
     )))
      // ->setContentType('text/html')
    ;

    $this->getMailer()->send($message);
  }

}
